package com.zengqingfa.examples.mybatisplus.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.zengqingfa.examples.mybatisplus.common.CommonConstants;
import com.zengqingfa.examples.mybatisplus.dto.DynamicColumnInfoDTO;
import com.zengqingfa.examples.mybatisplus.dto.DynamicColumnUpdateDTO;
import com.zengqingfa.examples.mybatisplus.entity.DynamicColumn;
import com.zengqingfa.examples.mybatisplus.enums.DynamicColumnModuleEnum;
import com.zengqingfa.examples.mybatisplus.mapper.DynamicColumnMapper;
import com.zengqingfa.examples.mybatisplus.service.IDynamicColumnService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 动态列表 服务实现类
 * </p>
 *
 * @author slfx
 * @since 2022-11-03
 */
@Service
public class DynamicColumnServiceImpl extends ServiceImpl<DynamicColumnMapper, DynamicColumn> implements IDynamicColumnService {
    /**
     * 资产台账分页列表列名映射
     */
    private static final Map<Integer, List<DynamicColumnInfoDTO>> COLUMN_DEFAULT_MAPPING;

    @Override
    public List<DynamicColumnInfoDTO> queryDynamicColumn(Integer module, String userId) {
        Gson gson = new Gson();
        LambdaQueryWrapper<DynamicColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DynamicColumn::getModule, module)
                .eq(DynamicColumn::getCreateBy, userId)
                .eq(DynamicColumn::getDeleted, CommonConstants.NOT_DELETED);
        DynamicColumn dynamicColumn = this.baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(dynamicColumn)) {
            // 找不到当前用户指定模块的动态列表，则返回默认动态列表
            return COLUMN_DEFAULT_MAPPING.get(module);
        }
        return gson.fromJson(dynamicColumn.getColumnInfo(), new TypeToken<List<DynamicColumnInfoDTO>>() {
        }.getType());
    }

    /**
     * 动态列表更新
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean updateDynamicColumn(DynamicColumnUpdateDTO dto, String userId) {
        List<DynamicColumnInfoDTO> defaultColumnList = COLUMN_DEFAULT_MAPPING.get(dto.getModule());
        defaultColumnList = defaultColumnList == null ? new ArrayList<>() : defaultColumnList;
        final Map<String, DynamicColumnInfoDTO> columnMap = defaultColumnList.stream().collect(Collectors.toMap(DynamicColumnInfoDTO::getField, Function.identity()));
        // 获得动态列表信息列表
        List<DynamicColumnInfoDTO> dynamicColumnInfoDTOList = dto.getColumnInfo().stream()
                .map(columnInfoRequest -> {
                    DynamicColumnInfoDTO dynamicColumnInfoDTO = new DynamicColumnInfoDTO();
                    dynamicColumnInfoDTO.setField(columnInfoRequest.getField());
                    dynamicColumnInfoDTO.setDesc(columnMap.get(columnInfoRequest.getField()) == null ? "" : columnMap.get(columnInfoRequest.getField()).getDesc());
                    dynamicColumnInfoDTO.setShow(columnInfoRequest.getShow());
                    dynamicColumnInfoDTO.setOrder(columnInfoRequest.getOrder());
                    dynamicColumnInfoDTO.setFixed(columnInfoRequest.getFixed());
                    dynamicColumnInfoDTO.setDatabaseField(columnInfoRequest.getDatabaseField());
                    return dynamicColumnInfoDTO;
                })
                .collect(Collectors.toList());

        LambdaQueryWrapper<DynamicColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DynamicColumn::getModule, dto.getModule())
                .eq(DynamicColumn::getCreateBy, userId)
                .eq(DynamicColumn::getDeleted, CommonConstants.NOT_DELETED);
        // 查询数据库中当前用户指定模块的动态列表
        DynamicColumn existsDynamicColumn = this.baseMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(existsDynamicColumn)) {
            // 数据库中存在当前用户指定模块的动态列表信息，则做更新操作
            LambdaQueryWrapper<DynamicColumn> updateWrapper = new LambdaQueryWrapper<>();
            existsDynamicColumn.setColumnInfo(JSONArray.toJSONString(dynamicColumnInfoDTOList));
            updateWrapper.eq(DynamicColumn::getId, existsDynamicColumn.getId());
            this.update(existsDynamicColumn, updateWrapper);
        } else {
            // 数据库中不存在当前用户指定模块的动态列表信息，则做新增操作
            DynamicColumn dynamicColumn = new DynamicColumn();
            dynamicColumn.setModule(dto.getModule());
            dynamicColumn.setColumnInfo(JSONArray.toJSONString(dynamicColumnInfoDTOList));
            dynamicColumn.setCreateBy(userId);
            dynamicColumn.setCreateTime(LocalDateTime.now());
            dynamicColumn.setUpdateBy(userId);
            dynamicColumn.setUpdateTime((LocalDateTime.now()));
            dynamicColumn.setDeleted(CommonConstants.NOT_DELETED);
            this.save(dynamicColumn);
        }
        return true;
    }

    static {
        // 初始动态列表列名映射
        COLUMN_DEFAULT_MAPPING = new HashMap<>();
        for (DynamicColumnModuleEnum e : DynamicColumnModuleEnum.values()) {
            if (e.getVoClazz() != null) {
                COLUMN_DEFAULT_MAPPING.put(e.getType(), genColumnDefaultMapping(e.getVoClazz()));
            }
        }

    }

    /**
     * 获得列映射
     *
     * @param clazz clazz
     * @return {@link Map}<{@link String},{@link String}>
     */
    private static List<DynamicColumnInfoDTO> genColumnDefaultMapping(Class<?> clazz) {
        List<DynamicColumnInfoDTO> defaultColumnList = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        int i = 0;
        for (Field field : fields) {
            if (field.isAnnotationPresent(ApiModelProperty.class)) {
                ApiModelProperty property = field.getAnnotation(ApiModelProperty.class);
                DynamicColumnInfoDTO dynamicColumnInfoDTO = new DynamicColumnInfoDTO();
                dynamicColumnInfoDTO.setField(field.getName());
                dynamicColumnInfoDTO.setDatabaseField(StrUtil.toUnderlineCase(field.getName()));
                dynamicColumnInfoDTO.setDesc(property.value());
                dynamicColumnInfoDTO.setShow(true);
                dynamicColumnInfoDTO.setOrder(i++);
                defaultColumnList.add(dynamicColumnInfoDTO);
            }
        }
        return defaultColumnList;
    }
}
